# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : schedule_utils.py
# Time       ：2023/11/5 15:34
# Author     ：Y-aong
# version    ：python 3.10
# Description：
"""
from apis.schedule_plan.models import CrontabPlan, DatePlan, IntervalPlan, ApschedulerJobs
from apis.schedule_plan.schema.schedule_plan_schema import CrontabPlanSchema, DatePlanSchema, IntervalPlanSchema, \
    ApschedulerJobsSchema
from public.base_model import session_scope


class ScheduleUtils:

    @staticmethod
    def handle_interval_schedule_plan(schedule_plan: dict):
        """处理定时计划参数"""
        data = dict()
        data[schedule_plan.get('interval_type')] = schedule_plan.get('interval_val')
        data['start_date'] = schedule_plan.get('start_date')
        data['end_date'] = schedule_plan.get('end_date')
        return data
    @staticmethod
    def get_schedule_plan(trigger, schedule_plan_id):
        table_orms = {
            'cron': CrontabPlan,
            'date': DatePlan,
            'interval': IntervalPlan
        }
        table_schemas = {
            'cron': CrontabPlanSchema,
            'date': DatePlanSchema,
            'interval': IntervalPlanSchema
        }

        table_orm = table_orms.get(trigger)
        table_schema = table_schemas.get(trigger)
        if not table_orm or not table_schema:
            raise ValueError(f'trigger {trigger} is not invalid')
        data = dict()
        if table_orm:
            with session_scope() as session:
                schedule_plan_obj = session.query(table_orm).filter(table_orm.id == schedule_plan_id).first()

            schedule_plan = table_schema().dump(schedule_plan_obj)
            for key, val in schedule_plan.items():
                if schedule_plan.get(key):
                    data.setdefault(key, val)
        if trigger == 'interval':
            interval_plan = dict()
            for key, val in data.items():
                if key not in ['start_date', 'end_date', 'job_id']:
                    interval_plan['interval_type'] = key
                    interval_plan['interval_val'] = val
                else:
                    interval_plan[key] = val
            return interval_plan
        else:
            return data

    def get_next_run_time(self, trigger, plan_name, schedule_plan):
        """获取定时任务下次运行时间"""
        if trigger == 'date':
            return schedule_plan.get('schedule_plan')
        else:
            with session_scope() as session:
                obj = session.query(ApschedulerJobs).filter(ApschedulerJobs.id == plan_name).first()
            if obj:
                info = ApschedulerJobsSchema().dump(obj)
                return info.get('next_run_time')
            else:
                return ''
